package com.angel.webapp.servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.angel.architecture.exceptions.NonBusinessException;
import com.angel.common.keyValue.KeyValueResult;
import com.angel.webapp.actions.ActionStrategy;
import com.angel.webapp.application.ApplicationActionStrategies;
import com.angel.webapp.file.FileInformation;
import com.angel.webapp.keyValue.SearchParametersKeyValueResult;

/**
 * @author William
 * @since 13/August/2009
 */
public class DownloadEmailAttachmentServlet extends DownloadServlet {

	protected static final String ACTION_STRATEGY_NAME_REQ_PARAMETER = "actionStrategyName";
	
	protected static final String EMAIL_PARAMETERS_REQ_PARAMETER = "emailParamaters";
	
	private static final long serialVersionUID = -3412999917186927615L;

	@Override
    protected FileInformation doProcess(KeyValueResult properties, final HttpServletRequest request, final HttpServletResponse response) {
		
		String actionStrategyName = properties.getResultFor(ACTION_STRATEGY_NAME_REQ_PARAMETER).toString();
		String emailParamaters = properties.getResultFor(EMAIL_PARAMETERS_REQ_PARAMETER).toString();

		String emailSeparatorParamaters = DEFAULT_SEPARATOR_PARAMETERS;
		if(properties.containsResultFor(REQ_PARAMETER_SEPARATOR_PARAMETERS)){
			emailSeparatorParamaters = properties.getResultFor(REQ_PARAMETER_SEPARATOR_PARAMETERS).toString();
		}

		ActionStrategy actionStrategy = ApplicationActionStrategies.createInstance().findActionStrategy(actionStrategyName);
		KeyValueResult actionParamaters = new SearchParametersKeyValueResult(emailParamaters, emailSeparatorParamaters);
		
		FileInformation fileInformation = actionStrategy.doAction(actionParamaters);

		return fileInformation;
    }

	@Override
    protected void doCheckParameters(KeyValueResult properties) {
		boolean containsActionStrategyName = properties.containsResultFor(ACTION_STRATEGY_NAME_REQ_PARAMETER);
		boolean containsEmailParamaters = properties.containsResultFor(EMAIL_PARAMETERS_REQ_PARAMETER);
		if(!containsActionStrategyName || containsEmailParamaters){
			throw new NonBusinessException("Action strategy name and email parameters must be added to request. ");
		}
    }
}
